package benny.ApkposStore.Activity;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import benny.ApkposStore.R;
import benny.ApkposStore.R.string;
import benny.ApkposStore.Service.OrderSyncService;
import benny.ApkposStore.utils.ApkConstant;
import benny.ApkposStore.utils.ApkUntils;
import benny.ApkposStore.utils.Apkglobal;
import benny.ApkposStore.utils.FileUtils;
import benny.ApkposStore.utils.HttpDownloader;
import benny.ApkposStore.utils.NetUtils;

public class ApkposStoreActivity extends Activity {
	/** Called when the activity is first created. */
	private EditText usertext = null;
	private EditText passwordtext = null;
	private EditText cardtext = null;
	private GridView gridView = null;
	private ListAdapter menuAdapter = null;
	private Button softkeyButton = null;
	private Button configuresvc = null;
	private Button copyrightbtn = null;
	private Button synchronization = null;
	private TextView synTextView = null;
	private Button landButton = null;
	private Button exitButton = null;
	private AlertDialog.Builder builder = null;
	private String tag = "ApkposStoreActivity";
	// 引用mideaPlayer和SoundPool
	MediaPlayer mMediaPlayer;
	SoundPool soundPool;
	HashMap<Integer, Integer> soundPoolMap;
	private Button requestButton;
	private boolean keydown=false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ApkUntils.fullscreen(this);
		setContentView(R.layout.main);
		initSounds();
		if (Apkglobal.getuuid()==null) {
			Apkglobal.setuuid(ApkUntils.getMyUUID(this));
		}
		if (Apkglobal.getcdkey().length()==0) {
			String CDKEY = ApkUntils.ReadSharedPreferences(
					ApkposStoreActivity.this, "CDKEY", "cdkey");
			Apkglobal.setcdkey(CDKEY);
		}
		gridView = (GridView) this.findViewById(R.id.gridview_softkeyboard);
		if (Apkglobal.getkey_false()) {
			Apkglobal.setkey_false(false);
		} // 恢复全局变量 key_false
		Intent intent = new Intent();
		// float bl = ApkUntils.getPixelsintH(this);
		// float bw = ApkUntils.getPixelsintW(this);
//		intent.setClass(ApkposStoreActivity.this, ResponseService.class);
//		startService(intent);// 启动下载

		intent.setClass(ApkposStoreActivity.this, OrderSyncService.class);
		startService(intent);// 启动后台上传订单
       
		menuAdapter = ApkUntils.getMenuAdapter(this);
		synTextView = (TextView) findViewById(R.id.textview_syn);
		usertext = (EditText) findViewById(R.id.usernametext);
		passwordtext = (EditText) findViewById(R.id.passwordtext);
		requestButton = (Button) findViewById(R.id.request_test);
		cardtext = (EditText) findViewById(R.id.cardtext);
		softkeyButton = (Button) findViewById(R.id.apkbtn);
		exitButton = (Button) findViewById(R.id.shutdown);
		landButton = (Button) findViewById(R.id.landbtn1);
		configuresvc = (Button) findViewById(R.id.configuresvc);
		synchronization = (Button) findViewById(R.id.synchronization);
		synchronization.setOnClickListener(new synchronizationListener());
		copyrightbtn = (Button) findViewById(R.id.copyrightbtn);
		copyrightbtn.setOnClickListener(new copyrightbtnListener());
		configuresvc.setOnClickListener(new configuresvcListener());
		// usertext.setInputType(InputType.TYPE_NULL);
		// passwordtext.setInputType(InputType.TYPE_NULL);
		cardtext.setInputType(InputType.TYPE_NULL);
		landButton.setOnClickListener(new landListener());
		//softkeyButton.setOnClickListener(new softkeyListener());
		requestButton.setOnClickListener(new requestListener());
		exitButton.setOnClickListener(new exitButtonListener());
		builder = new Builder(ApkposStoreActivity.this);

		/*
		 * tp = synchronization.getPaint(); tp.setFakeBoldText(true); tp =
		 * configuresvc.getPaint(); tp.setFakeBoldText(true);
		 */
		/*
		 * usertext.setOnTouchListener(new OnTouchListener() {
		 * 
		 * @Override public boolean onTouch(View v, MotionEvent event) { switch
		 * (event.getAction()) {
		 * 
		 * case MotionEvent.ACTION_DOWN:
		 * et.setTransformationMethod(PasswordTransformationMethod
		 * .getInstance()); break;
		 * 
		 * case MotionEvent.ACTION_UP:
		 * 
		 * ApkUntils.opensoftkeyboard(usertext,gridView,menuAdapter,1); if
		 * (gridView.getVisibility() == View.INVISIBLE) {
		 * ApkUntils.ViewVisible(gridView); }
		 * 
		 * break; } return false; } });
		 */
		/*
		 * passwordtext.setOnKeyListener(new OnKeyListener() {
		 * 
		 * @Override public boolean onKey(View v, int keyCode, KeyEvent event) {
		 * // TODO Auto-generated method stub
		 * 
		 * if (keyCode == KeyEvent.KEYCODE_ENTER) { // 当按下enter 时候关闭软键盘
		 * 
		 * InputMethodManager m = (InputMethodManager)
		 * getSystemService(Context.INPUT_METHOD_SERVICE); m.toggleSoftInput(0,
		 * InputMethodManager.HIDE_NOT_ALWAYS); // autosearch.setText(""); }
		 * return false; } });
		 */

		passwordtext.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {

				case MotionEvent.ACTION_DOWN:
					passwordtext
							.setTransformationMethod(PasswordTransformationMethod
									.getInstance());
					break;

				// case MotionEvent.ACTION_UP:
				// ApkUntils.opensoftkeyboard(passwordtext,gridView,menuAdapter,1);
				// if (gridView.getVisibility() == View.INVISIBLE) {
				// ApkUntils.ViewVisible(gridView);
				// }
				//
				// break;
				}
				return false;
			}
		});

		cardtext.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					cardtext.setTransformationMethod(PasswordTransformationMethod
							.getInstance());
					// cardtext.setCursorVisible(false);
					break;

				case MotionEvent.ACTION_UP:
					if (gridView != null) {

						if (gridView.getVisibility() == View.VISIBLE) {
							ApkUntils.ViewInvisible(gridView);
						}
					}
					break;
				}
				return false;
			}
		});
		
	}

	class downloadReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			String msgString = arg1.getStringExtra("msgStr");
			synTextView.setText(msgString);
		}

	}

	class synchronizationListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			AsyncGetShopConfig asyncGetShopConfig = new AsyncGetShopConfig();
			asyncGetShopConfig.setCdKey(Apkglobal.getcdkey());
			asyncGetShopConfig.setUUID(Apkglobal.getuuid());
			asyncGetShopConfig.execute();
		}

	}

	class requestListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			try {
				if (Apkglobal.getcdkey().length() > 0) {
					ApkUntils.WriteSharedPreferences(ApkposStoreActivity.this,
							"CDKEY", "cdkey", "");
					Apkglobal.setcdkey("");
				} else {
					Apkglobal.setcdkey("20EK2-R49W4-VKS1S-19BVY");
					Apkglobal.setuuid(ApkUntils
							.getMyUUID(ApkposStoreActivity.this));
					ApkUntils.WriteSharedPreferences(ApkposStoreActivity.this,
							"CDKEY", "cdkey", "20EK2-R49W4-VKS1S-19BVY");
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	// 异步登陆任务
	private class AsyncLogin extends AsyncTask<Void, Void, Integer> {
		private String mCdKey = "";
		private String mUUID = "";
		private String mUserName = "";
		private String mPwd = "";
		private String msg = "登陆失败，请重新尝试！";
		private ProgressDialog progressDialog = null;

		public void setCdKey(String cdKey) {
			mCdKey = ApkUntils.escape(cdKey);
		}

		public void setUUID(String uuid) {
			mUUID = ApkUntils.escape(uuid);
		}

		public void setUersName(String username) {
			mUserName = ApkUntils.escape(username);
		}

		public void setPwd(String pwd) {
			mPwd = ApkUntils.escape(pwd);
		}

		@Override
		protected Integer doInBackground(Void... params) {
			String url = ApkConstant.BaseLoginUrl;
			try {
				String postParams = "type=0&" + "cdkey=" + mCdKey + "&"
						+ "uuid=" + mUUID + "&" + "username=" + mUserName + "&"
						+ "pwd=" + mPwd;
				String data = NetUtils.fetchTextFromPost(url, postParams);

				JSONObject jsonObj = new JSONObject(data);
				if (jsonObj.getInt("ret") != 0) {
					Log.e(tag,
							"AsyncLogin: login failed:"
									+ jsonObj.getString("msg"));
					msg = "登陆失败！" + jsonObj.getString("msg");
					return -1;
				}

				Apkglobal.settoken(jsonObj.getString("token"));
				Apkglobal.setuser_name(jsonObj.getString("username"));
				Apkglobal.setuser_id(jsonObj.getString("userid"));
				Apkglobal.setrealname(jsonObj.getString("realname"));
				Apkglobal.setshopname(jsonObj.getString("shop_name"));
				Apkglobal.setcompanyname(jsonObj.getString("company_name"));
				Apkglobal.setposid(jsonObj.getString("odno_id"));

				return 0;
			} catch (Exception e) {
				Log.e(tag, "AsyncLogin:" + e.getMessage());
				msg = e.getMessage();
			}

			return -1;
		}

		// 在doInBackground前执行
		protected void onPreExecute() {
			// TODO: 显示正在登陆的提示

			// progressDialog = ProgressDialog.show(ApkposStoreActivity.this,
			// "请稍等...", "正在登陆中...", true);
			progressDialog = new ProgressDialog(ApkposStoreActivity.this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setIcon(R.drawable.apkn);
			progressDialog.setTitle("请稍等...");
			progressDialog.setMessage("正在登陆...");
			progressDialog.setCancelable(true);
			progressDialog.show();
		}

		// 在doInBackground后执行
		protected void onPostExecute(Integer result) {
			progressDialog.dismiss(); // TODO: 取消正在登陆的提示
			if (result == 0) {
				// login ok
				FileUtils filedb = new FileUtils();
				if (!filedb.isapkFileExist("shop_config.db", "databases/")) {
					Builder builderdd = new Builder(ApkposStoreActivity.this);
					dialog1(builderdd, "检测到当前系统没有基础数据，请先进行数据下载！",
							string.dialog_title1,
							android.R.drawable.ic_dialog_info);
					return;
				}
				// 启动房台界面
				Intent intent = new Intent();
				intent.setClass(ApkposStoreActivity.this,
						RoomtableActivity.class);
				startActivity(intent);
				ApkUntils.openActivityAnim(ApkposStoreActivity.this, 10);
				finish();
			} else if (result == -1) {
				// TODO: login failed，取消正在登陆的提示，换成提示登陆失败
				Builder builderdd = new Builder(ApkposStoreActivity.this);
				dialog1(builderdd, msg, string.dialog_title1,
						android.R.drawable.ic_dialog_info);
			}
		}
	}

	// 异步获取配置SQLite
	private class AsyncGetShopConfig extends AsyncTask<Void, Integer, Integer> {
		private String mUUID = "";
		private String mCdKey = "";
		private int mContentLength = 0;
		private ProgressDialog progressDialog;
		private String msg = "下载失败，请重新尝试！";

		public void setCdKey(String cdKey) {
			mCdKey = cdKey;
		}

		public void setUUID(String uuid) {
			mUUID = uuid;
		}

		@Override
		protected Integer doInBackground(Void... params) {
			String url = ApkConstant.BaseSqliteUrl;
			String postParams = "type=all&cdkey=" + mCdKey + "&" + "uuid="
					+ mUUID;

			FileUtils.WritingProgress progress = new FileUtils.WritingProgress() {
				@Override
				public void onProgress(int already) {
					publishProgress((int) ((float) already * 100 / mContentLength));
				}
			};

			try {
				HttpURLConnection connection = NetUtils
						.getHttpPostConnection(url);
				DataOutputStream outputStream = new DataOutputStream(
						connection.getOutputStream());
				outputStream.write(postParams.getBytes());// 发送表单字段数据
				outputStream.flush();

				int retCode = connection.getResponseCode();
				mContentLength = connection.getContentLength();
				Log.d(tag, "retCode:" + retCode + " length:" + mContentLength);
				if (retCode == 200) {
					String connectEncode = connection.getContentEncoding();
					InputStream inputStream = null;
					if (!TextUtils.isEmpty(connectEncode)
							&& connectEncode.contains("gzip")) {
						inputStream = new GZIPInputStream(
								connection.getInputStream());
					} else {
						inputStream = connection.getInputStream();
					}

					if (connection.getContentType().equals(
							"application/octet-stream")) {
						// binery data, save to file
						FileUtils fileUtils = new FileUtils();
						fileUtils.atomWrite2SDFromInput("databases/",
								"shop_config.db", inputStream, progress);
						return 0;
					} else {
						// error JSON message
						char[] buffer = new char[1024];
						StringBuilder strbuilder = new StringBuilder();
						int len = (new InputStreamReader(inputStream, "UTF-8"))
								.read(buffer);
						strbuilder.append(buffer, 0, len);

						JSONObject jsonObj = new JSONObject(
								strbuilder.toString());
						Log.e(tag,
								"AsyncGetShopConfig: download config file failed,ret:"
										+ jsonObj.getInt("ret") + ",msg:"
										+ jsonObj.getString("msg"));
						msg = "下载失败！" + jsonObj.getString("msg");
						return -1;
					}
				}
			} catch (Exception e) {
				Log.e(tag, "AsyncGetShopConfig:" + e.getMessage());
				msg = "下载失败！" + e.getMessage();
				return -1;
			}

			return -1;
		}

		protected void onPreExecute() {
			// TODO: 显示正在获取配置的进度条
			progressDialog = new ProgressDialog(ApkposStoreActivity.this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			progressDialog.setIcon(R.drawable.apkn);
			progressDialog.setTitle("请稍等...");
			progressDialog.setMessage("正在下载基础信息...");
			progressDialog.setProgress(0);
			progressDialog.setMax(100);
			progressDialog.show();
		}

		protected void onPostExecute(Integer result) {
			// TODO: 取消进度条
			progressDialog.dismiss();
			if (result == 0) {
				synTextView.setText("同步成功");
			} else if (result == -1) {
				// TODO: login failed，取消正在激活的提示，换成提示激活失败
				Builder builderdd = new Builder(ApkposStoreActivity.this);
				dialog1(builderdd, msg, string.dialog_title1,
						android.R.drawable.ic_dialog_info);
			}
		}

		protected void onProgressUpdate(Integer... progress) {
			// TODO: 更新进度条的进度
			Log.d(tag, "downloading file progress:" + progress[0]);
			progressDialog.setProgress(progress[0]);
		}

	}

	private void dialog1(AlertDialog.Builder builder, String msg,
			int dialogTitle1, Integer icon) {
		builder.setMessage(msg);
		builder.setTitle(dialogTitle1);
		builder.setIcon(icon);
		builder.setNegativeButton("关闭", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}

		});

		builder.create().show();

	}

	public void httppost(String url, String flag) throws Exception {
		// Get的URL
		HttpPost httpRequest = new HttpPost(url);
		HttpDownloader hDownloader = new HttpDownloader();

		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse httpResponse = httpclient.execute(httpRequest);
		Header header = httpResponse.getFirstHeader("Content-type");
		String type = header.getValue();
		String resultString = null;
		if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			if (flag.equals('D'))// 下载菜品数据
			{
				if (type.equals("application/octet-stream")) {
					InputStream inputStream = httpResponse.getEntity()
							.getContent();
					int result = hDownloader.saveFile(inputStream, "Date/",
							"shop_config.db");
					if (result == -1) {
						resultString = "下载失败！";
					} else if (result == 0) {
						resultString = "下载成功！";
					} else if (result == 1) {
						resultString = "该文件已经存在！";
					}

				} else {
					String jsonStr = EntityUtils.toString(
							httpResponse.getEntity(), "UTF-8");
					JSONObject jjsss = new JSONObject(jsonStr);
					resultString = jjsss.get("msg").toString();
				}

			} else if (flag.equals("J"))// 激活CDKEY
			{
				String jsonStr = EntityUtils.toString(httpResponse.getEntity(),
						"UTF-8");

				JSONObject jjsss = new JSONObject(jsonStr);
				String sucess = jjsss.get("ret").toString();

				if (sucess.equals("0")) {
					resultString = "激活成功！";
				} else {

					resultString = jjsss.get("msg").toString();
				}

			} else if (flag.equals("Q"))// 权限
			{
				String jsonStr = EntityUtils.toString(httpResponse.getEntity(),
						"UTF-8");

				JSONObject jjsss = new JSONObject(jsonStr);
				String sucess = jjsss.get("ret").toString();
				if (sucess.equals("0")) {
					resultString = "有效权限！";
				} else {

					resultString = jjsss.get("msg").toString();
				}

			} else if (flag.equals("L"))// 登陆
			{
				String jsonStr = EntityUtils.toString(httpResponse.getEntity(),
						"UTF-8");
				JSONObject jjsss = new JSONObject(jsonStr);
				String sucess = jjsss.get("ret").toString();
				if (sucess.equals("0")) {
					Apkglobal.settoken(jjsss.get("token").toString());
					Apkglobal.setuser_name(jjsss.get("username").toString());
					Apkglobal.setuser_id(jjsss.get("userid").toString());
					Apkglobal.setrealname(jjsss.get("realname").toString());
					Apkglobal.setshopname(jjsss.get("shop_name").toString());
					Apkglobal.setcompanyname(jjsss.get("company_name")
							.toString());

					Intent intent = new Intent();
					intent.setClass(ApkposStoreActivity.this,
							RoomtableActivity.class);
					startActivity(intent);
					ApkUntils.openActivityAnim(ApkposStoreActivity.this, 10);
					finish();
					return;
				} else {

					resultString = jjsss.get("msg").toString();
				}

			}

			// 打印输出
			// 如果是下载文件,可以用response.getEntity().getContent()返回InputStream
		} else {
			resultString = "请求失败，请重新尝试！";
		}

		Toast.makeText(getApplicationContext(), resultString, Toast.LENGTH_LONG)
				.show(); // 进入loop中的循环，查看消息队列
	}

	class copyrightbtnListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent();
			intent.setClass(ApkposStoreActivity.this, MainhttpActivity.class);
			startActivity(intent);
		}

	}

	class configuresvcListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent();
			intent.setClass(ApkposStoreActivity.this, LandhttpActivity.class);
			startActivity(intent);
		}

	}

	class softkeyListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			if (!Apkglobal.getkey_false()) {
				ApkUntils.opensoftkeyboard(passwordtext, gridView, menuAdapter,
						1);
				usertext.requestFocus();
			}
			if (gridView.getVisibility() == View.INVISIBLE) {
				// ApkUntils.ViewVisible(gridView);
				Animation animation1 = AnimationUtils.loadAnimation(
						getApplicationContext(), R.anim.slide_up_in);
				gridView.setAnimation(animation1);
				gridView.setVisibility(View.VISIBLE);

			} else {
				// ApkUntils.ViewInvisible(gridView);
				Animation animation2 = AnimationUtils.loadAnimation(
						getApplicationContext(), R.anim.slide_down_out);
				gridView.setAnimation(animation2);
				gridView.setVisibility(View.INVISIBLE);
			}

		}

	}

	class exitButtonListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (keydown) {
				return;
			}
			try {
				keydown=true;
				playSound(1, 0);
				dialog(builder, string.quit_msg, string.dialog_title1,
						android.R.drawable.ic_dialog_info);
				keydown=false;
			} catch (Exception e) {
				// TODO: handle exception
				keydown=false;
				Log.e(tag, e.getMessage());
			}
		
			// shutdown();
		}

	}

	/**
	 * 初始化声音的方法
	 */
	public void initSounds() {
		// mMediaPlayer = MediaPlayer.create(this, R.raw.music);
		soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
		soundPoolMap = new HashMap<Integer, Integer>();
		soundPoolMap.put(1, soundPool.load(this, R.raw.logoff, 1));
		soundPoolMap.put(2, soundPool.load(this, R.raw.bird, 2));
	}

	/**
	 * 播放音效的方法
	 */
	public void playSound(int sound, int loop) {
		AudioManager mgr = (AudioManager) this
				.getSystemService(Context.AUDIO_SERVICE);
		float streamVolumeCurrent = mgr
				.getStreamVolume(AudioManager.STREAM_MUSIC);
		float streamVolumeMax = mgr
				.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		float volume = streamVolumeCurrent / streamVolumeMax;
		soundPool.play(soundPoolMap.get(sound), volume, volume, 1, loop, 1f);
	}

	class landListener implements OnClickListener {

		@Override
		public void onClick(View v) {

			AsyncLogin asyncLogin = new AsyncLogin();
			asyncLogin.setCdKey(Apkglobal.getcdkey());
			asyncLogin.setUUID(Apkglobal.getuuid());
			asyncLogin.setUersName(usertext.getText().toString());
			asyncLogin.setPwd(passwordtext.getText().toString());
			asyncLogin.execute();
		}

	}

	private void dialog(AlertDialog.Builder builder, int quitMsg,
			int dialogTitle1, Integer icon) {
		builder.setMessage(quitMsg);
		builder.setTitle(dialogTitle1);
		builder.setIcon(icon);
		builder.setPositiveButton(string.ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
						ApkUntils.quit(ApkposStoreActivity.this);
					}

				});
		builder.setNegativeButton(string.cancal,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}

				});

		builder.create().show();

	}

	protected void shutdown() {

		// 目前最为通用的 关闭进程的方法以后的版本使用
		Intent newIntent = new Intent(Intent.ACTION_SHUTDOWN);
		newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(newIntent);

	}

	@Override
	protected void onDestroy() {
		System.gc(); // 回收系统资源
		super.onDestroy();
	}

}
